<template>
  <div class="container">
    <div class="content">
      <p class="title">一站式系统</p>
      <el-form ref="formRef" :model="request" :rules="rules">
        <el-form-item prop="username" label="账号">
          <el-input @keyup.enter="login" v-model.trim="request.username" placeholder="请输入账号" clearable>
            <template #prefix>
              <el-icon class="el-input__icon">
                <user/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input @keyup.enter="login" v-model.trim="request.password" placeholder="请输入密码"
                    clearable type="password" show-password>
            <template #prefix>
              <el-icon class="el-input__icon">
                <DataAnalysis/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="">
          <el-button type="primary" @click="login('form')" style="width: 100%">登 陆</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { loginUrl } from '@/api/api'
import { reactive, ref } from 'vue'
import { post } from '@/utils/httpRequest'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { loginRules } from '@/utils/verifyForm'

export default {
  name: 'login',
  setup () {
    const store = useStore()
    const formRef = ref()
    const router = useRouter()
    // 请求数据
    const request = reactive({
      username: null,
      password: null
    })
    // 验证规则
    const rules = reactive(loginRules)
    // 登录
    const login = () => {
      formRef.value.validate().then(async () => {
        const result = await post(loginUrl, request)
        if (result.code === 200) {
          localStorage.setItem('tokenName', result.data.tokenName)
          localStorage.setItem('tokenValue', result.data.tokenValue)
          await store.dispatch('setMenuList')
          await router.push({
            path: '/'
          })
        }
      }).catch(error => {
        console.log(error)
      })
    }
    return {
      request,
      rules,
      formRef,
      login
    }
  }
}
</script>

<style scoped lang="less">
.container {
  background-image: url("../assets/images/bg.jpg");
  background-position: center;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;

  .content {
    padding: 0px 20px;
    background: #fff;
    border-radius: 5px;
    width: 350px;

    .title {
      text-align: center;
      margin-top: 20px;
      margin-bottom: 10px;
      font-size: 20px;
    }
  }
}
</style>
